package com.rcnie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rcnie.common.R;
import com.rcnie.entity.User;
import com.rcnie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody User user){
        //获取用户信息
        String username = user.getUsername();
        String password = user.getPassword();
        //md5加密
        String md5password = DigestUtils.md5DigestAsHex(password.getBytes());

        //根据username查询用户信息
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername,username);
        User userResult = userService.getOne(userLambdaQueryWrapper);
        //查询不到
        if(userResult==null){
            return R.error("没有用户");
        }else{//查询到，对比密码
            if(!md5password.equals(userResult.getPassword())){
                return R.error("密码错误");
            }
        }
        //密码正确相等返回R用户信息，将id存入session
        request.getSession().setAttribute("userId",userResult.getId());



        return R.succes(user);
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public R<User> register(@RequestBody User user){
        //获取数据
        String username = user.getUsername();
        String password = user.getPassword();
        //判断用户名是否存在数据库
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,username);
        User one = userService.getOne(lambdaQueryWrapper);
        //判断是否存在用户
        if(one!=null){//用户存在
            System.out.println("用户存在");
            return R.error("用户已经存在");
        }
        //md5加密password
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        //随机生成id
        String randomID = UUID.randomUUID().toString().substring(0, 8);
        user.setId(randomID);
        //不是则添加用户
        userService.save(user);

        redisTemplate.boundValueOps("test").set("testvalue");
        //返回注册成功
        return R.succes(user);
    }
}
